package com.aiatomic.couting.password;

import org.json.JSONException;
import org.json.JSONObject;

import com.aiatomic.couting.CoutingApplication;
import com.aiatomic.couting.ICodeMsg;
import com.aiatomic.couting.PasswordForgetActivity;
import com.aiatomic.couting.R;
import com.aiatomic.couting.RegisterActivity;
import com.aiatomic.couting.util.ValidatorUtils;

import android.app.Fragment;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class FragmentForgetPassword2 extends Fragment {
	private String aid;
	private String phone;
	private View view;
	private Button btn_next;
	private EventHandler eh;
	private Handler handler = new Handler();
	private String msg = "发生未知错误";

	public FragmentForgetPassword2(String aid, String phone) {
		super();
		this.aid = aid;
		this.phone = phone;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment_password_forget2, container, false);
		TextView txtBack = (TextView) view.findViewById(R.id.txtBack);
		txtBack.setText(R.string.back);
		txtBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getActivity().onBackPressed();
			}
		});
		TextView txtNext = (TextView) view.findViewById(R.id.txtNext);
		txtNext.setVisibility(View.INVISIBLE);

		TextView txtMiddle = (TextView) view.findViewById(R.id.txtMiddle);
		txtMiddle.setText(R.string.get_forget_pass);
		btn_next = (Button) view.findViewById(R.id.btn_next);
		init();
		initSMS();
		return view;
	}

	private void init() {
		view.findViewById(R.id.get_sms_code_tips).setVisibility(View.GONE);
		final Button btn_sm = (Button) view.findViewById(R.id.get_sms);
		btn_sm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				view.findViewById(R.id.get_sms_code_tips).setVisibility(View.VISIBLE);
				((TextView) view.findViewById(R.id.get_sms_code_tips))
						.setText(String.format(getResources().getString(R.string.sms_send_msg), phone));
				btn_sm.setEnabled(false);
				CountDownTimer timer = new CountDownTimer(CoutingApplication.SMS_TIME, 1000) {
					@Override
					public void onTick(long millisUntilFinished) {
						String txtRepeat = String.format(getResources().getString(R.string.repeat_sms_code),
								millisUntilFinished / 1000);
						btn_sm.setText(txtRepeat);
					}

					@Override
					public void onFinish() {
						btn_sm.setText(R.string.get_sms_code);
						btn_sm.setEnabled(true);
					}
				};
				timer.start();

				SMSSDK.getVerificationCode("86", phone);
			}
		});
		view.findViewById(R.id.btn_next).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				TextView txtSmsCode = (TextView) view.findViewById(R.id.sms_code);
				if (txtSmsCode.getText().toString().isEmpty()) {
					txtSmsCode.setError(getResources().getString(R.string.err_input_sms_code));
					txtSmsCode.setFocusable(true);
					return;
				}
				SMSSDK.submitVerificationCode("86", phone, txtSmsCode.getText().toString().trim());
				btn_next.setEnabled(false);
				
			}
		});
	}
	private void initSMS() {

		SMSSDK.setAskPermisionOnReadContact(true);
		// 3.0版本之后的初始化看这里（包括3.0）
		eh = new EventHandler() {

			@Override
			public void afterEvent(int event, int result, Object data) {
				if (result == SMSSDK.RESULT_COMPLETE) {
					// 回调完成
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
						handler.post(new Runnable() {
							@Override
							public void run() {
								FragmentForgetPassword3 fr = new FragmentForgetPassword3(aid);
								PasswordForgetActivity passwordForgetActivity = (PasswordForgetActivity) FragmentForgetPassword2.this
										.getActivity();
								passwordForgetActivity.addFragment(fr);
							}
						});
						// 提交验证码成功
					} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
						System.out.println(data);
						// 获取验证码成功
					} else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
						// 返回支持发送验证码的国家列表
					}
				} else {

					Throwable e = (Throwable) data;
					e.printStackTrace();
					try {
						JSONObject err = new JSONObject(e.getMessage());
						int status = err.getInt("status");
						if (ICodeMsg.ERROR_CODES_SMS.containsKey(status)) {
							msg = ICodeMsg.ERROR_CODES_SMS.get(status);
						}
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
					handler.post(new Runnable() {
						@Override
						public void run() {
							btn_next.setEnabled(true);
							Toast toast = Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG);
							toast.setGravity(Gravity.CENTER, 0, 0);
							toast.show();

						}
					});

				}
			}
		};
		SMSSDK.registerEventHandler(eh); // 注册短信回调
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (eh != null) {
			SMSSDK.unregisterEventHandler(eh);
		}
	}
	
	
}
